package cn.wolfcode.interceptor;

import cn.wolfcode.redis.service.ISecurityRedisService;
import cn.wolfcode.util.JSONResult;
import cn.wolfcode.util.Md5Utils;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;


@Component
public class SignInterceptor implements HandlerInterceptor {

    @Autowired
    private ISecurityRedisService securityRedisService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取请求参数
        // 此处由于前段代码未修改，暂时注掉
//        Map<String, String[]> map = request.getParameterMap();
//        // 遍历参数
//        Set<String> keys = map.keySet();
//        HashMap<String, Object> params = new HashMap<>();
//        for (String key : keys) {
//            // 排除签名参数
//            if (!"sign".equalsIgnoreCase(key)) {
//                params.put(key, arrayToString(map.get(key)));
//            }
//        }
//        String signServer = Md5Utils.signatures(params);
//        String signClient = request.getParameter("sign");
//        if (!signServer.equals(signClient)) {
//            response.setContentType("application/json;charset=utf-8");
//            JSONResult error = JSONResult.error(501, "签名无效", "接口被篡改");
//            response.getWriter().write(JSON.toJSONString(error));
//             违规次数+1 <<<<<<<<<<<<<<<<<<<<<<<--
//            securityRedisService.addIllegalCount(request.getRemoteAddr());
//            return false;
//        }
        return true;

    }

    // 字符串数组转换为字符串
    private String arrayToString(String[] array) {
        StringBuilder sb = new StringBuilder();
        for (String s : array) {
            sb.append(s);
        }
        return sb.toString();
    }
}
